package org.example.struct.array;

import com.alibaba.fastjson.JSON;

/**
 * @author liyishan
 * @date 2024/9/9 13:51
 * @apiNote
 */

public class Test01652Decrypt {
    public static void main(String[] args) {
        int[] code = {2,4,9,3};
        int k = -2;
        int[] res =decrypt2(code, k);
        System.out.println(JSON.toJSON(res));
    }
    public static int[] decrypt(int[] code, int k) {
        int n = code.length;
        int flag = k > 0 ? 1 : -1;
        int[] res = new int[n];
        for (int index = 0; index < n; index++) {
            int sum = 0;
            int first = (index + flag + n) % n;
            int len = 0;
            while (Math.abs(len) < Math.abs(k)) {
                sum += code[(first + len + n) % n];
                len += flag;
            }
            res[index] = sum;
        }
        return res;
    }

    public static int[] decrypt2(int[] code, int k) {
        int n = code.length;
        if (k == 0) {
            return new int[n];
        }
        int[] res = new int[n];
        int[] newCode = new int[n * 2];
        System.arraycopy(code, 0, newCode, 0, n);
        System.arraycopy(code, 0, newCode, n, n);
        code = newCode;
        int l = k > 0 ? 1 : n + k;
        int r = k > 0 ? k : n - 1;
        int w = 0;
        for (int i = l; i <= r; i++) {
            w += code[i];
        }
        for (int i = 0; i < n; i++) {
            res[i] = w;
            w -= code[l];
            w += code[r + 1];
            l++;
            r++;
        }
        return res;
    }
}
